package org.example.client8000.job;

import org.example.SystemDemo.utils.StringUtil;
import org.example.SystemDemo.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

/**
 * @author world
 * @desc 主动发送心跳检测包
 */
@Configuration
@EnableScheduling
public class SchedulingHeartbeat {
    @Value("${server-ip}")
    private String serverIp;

    @Value("${run-index}")
    private Long runIndex;

    /**
     * 自动发送心跳包，间隔3s
     */
    @Scheduled(fixedRate = 3000)
    public void SendHeartbeat(){
        try {
            String response = new RestTemplate().getForObject(String.format("http://%s/api/v1/ref/refurbish?index=%s", serverIp, runIndex), String.class);
            System.out.printf("当前服务器id为：%s  向服务器 %s 发送心跳包 %s. Time: %s%n",runIndex,serverIp,("true".equals(response) ? "已接收" : "被拒绝"),TimeUtil.timestamp());
        } catch (RestClientException e) {
            // e.printStackTrace();
            System.out.println(TimeUtil.timestamp() + " 发送心跳包失败,请检查服务器状态 或 检查网络连接");
        }

    }

}
